(function() {

    var User = {
        queryInfo: function(_success) {
            console.log('query user info');
            var url = "../user/userInfo"; 
            Core.post(url, {}, (result) => {
                console.log('userInfo', result);
                if(result.msg == '用户未登录') {
                    location.href = '../login.html';
                    return;
                }
                var userInfo = result.data;
                Store.commit('setUsername', userInfo.name);
                _success(result.data);
            }, 'json');
        }
    };
    window.User = User;

    window.VP = function(obj) {
        console.log('--------- 废弃 start vue plus! ------------');
        console.log('--------- 废弃 end vue plus! ------------');
        return obj;
    };

    var postcCache = {};
    
    // 带缓存的请求，不带转圈
    $.postc = function(url, param, _call, type) {
        var paramJson = JSON.stringify(param);
        var key = url+paramJson;
        var cache = postcCache[key];
        if(cache != null) {
            // console.log('从缓存中获取');
            _call(cache);
            return;
        }
        if(type == null) {
            type = 'json';
        }
        $.post(url, param, (result) => {
            // 链接和参数一致则 保存到缓存
            postcCache[key] = result;
            _call(result);
        }, type);
    };

    window.console.json = function(title, obj) {
        console.log(title, JSON.stringify(obj));
    };

    var initPage = function(page) {
        if(page.pagin == null) {
            page.pagin = {
                total: 0,
                page: 1,
                rows: 15
            }
        };

        if(page.onQuery == null) {
            page.onQuery = function() {
                // console.log('onQuery');
                page.service.onQuery();
            };
        }

        if(page.onAdd == null) {
            page.onAdd = function() {
                // console.log('onAdd');
                page.service.onAdd();
            };
        }

        if(page.onEdit == null) {
            page.onEdit = function() {
                // console.log('onEdit');
                page.service.onEdit();
            };
        }

        if(page.onDelete == null) {

            page.onDelete = function() {
                // console.log('onDelete');
                page.service.onDelete();
            };
        }

        if(page.onPaginChange == null) {
            page.onPaginChange = function() {
                // console.log('onPaginChange');
                page.service.onPaginChange();
            }
        }

        if(page.onAddConfirm == null) {
            page.onAddConfirm = function() {
                page.service.onAddConfirm();
            }
        }

        if(page.onEditConfirm == null) {
            page.onEditConfirm = function() {
                page.service.onEditConfirm();
            }
        }

        if(page.onSortChange == null) {
            page.onSortChange = function(sortConfig) {
                page.service.onSortChange(sortConfig);
            }
        }

        page.fieldClick = function(field) {
            if(field == 'comCode' || field == 'comName') {
                page.$refs.comcodeDialog.open();
            }
        };

    };

    var pageStart = function() {
        if(window.App != null) {
            App.initPage = false;
        }
    };

    var pageLoad = function() {
        if(window.App != null) {
            App.initPage = true;
        }
    };

    var getService = function(page) {
        var config = page.config;
        console.log("config", config);
        // var defaultConfig = Util.clone(config);
        pageStart();
        var service = {
            sortConfig: null, // 排序配置
            config: config,
            page: page,
            module: page.module,
            buildUrl: function(type) {
                // return Constant.url + "crud/" + type;
                // return "../" + this.module + "/" + type;
                return "/space/crud/datagrid";
            },
            notLoad: function() {
                this.page.init = true;
			    this.page.loading = false;
            },
            loadData: function(_call) {
                console.log('当前模块', this.module);
                // 顺序获取数据
                
                this.page.init = true; // 提前完成初始化

                this.loadTable(() => {
                    if(_call != null) {
                        _call();
                    }
                    this.page.loading = false; // 完成页面加载
                    pageLoad();
                });
                
            },
            getQueryParam: function() {
                var pagin = page.pagin;
                var param = page.queryParam;
                var defaultSort = page.config.sortConfig;
                var sort = this.sortConfig;
                var queryParam = {
                    page: pagin.page, 
                    rows: pagin.rows
                };
                for(var key in param) {
                    if(param[key] != "") {
                        queryParam[key] = param[key];
                    }
                }
                // if(sort != null) {
                //     for(var key in sort) {
                //         if(sort[key] != "") {
                //             queryParam[key] = sort[key];
                //         }
                //     }
                // }
                if(!this.loadSort(queryParam, sort)) {
                    this.loadSort(queryParam, defaultSort);
                }
                queryParam.module = this.page.module;
                return queryParam;
            },
            loadSort: function(param, sort) {
                if(sort != null) {

                    if(sort.sortOrder != null && sort.sortField != null) {
                        param.sortField = sort.sortField;
                        param.sortOrder = sort.sortOrder;

                        return true;
                    }
                }
                return false;
            },
            onSortChange: function(sortConfig) {
                // page.config.sortConfig = sortConfig;
                this.sortConfig = sortConfig;
                page.onQuery();
            },
            loadTable: function(_success) {
                
                var url = this.buildUrl( "datagrid" );

                var pagin = page.pagin;
                
                var queryParam = this.getQueryParam();
                console.log("查询主表格条件", queryParam);

				$.post(url, queryParam, (data) => {
                    console.log( "查询主表格数据", data );
                    pagin.total = data.total;
					page.datagrid = data;
                    page.rows = data.rows;
                    
                    _success();
				}, 'json');
            },
            
            onQuery: function() {
                console.log('onQuery');
                page.loading = true;
                this.loadTable(() => {
                    page.loading = false;
                });
            },
            onAdd: function() {
                var dialog = page.$refs.editDialog;
                // page.form = {}; // 导致双向绑定解除？
                // page.form = Util.cloneBase( page.currentRow );
                dialog.open('新增');
            },
            isSelect: function() {
                // console.log('isSelect', page.currentRow);
                if(page.currentRow == null) {
                    UI.warning("请先选择一列");
                    return false;
                }
                return true;
            },
            onEdit: function() {
                if(this.isSelect()) {
                    var dialog = page.$refs.editDialog;
                    page.form = Util.cloneBase( page.currentRow );
                    dialog.open('编辑');
                }
            },
            onDelete: function() {
                if(this.isSelect()) {
                    UI.deleteConfirm(() => {
                        this.onDeleteConfirm();
                    });
                }
            },
            onAddConfirm: function () {
                console.log('on add confirm');
                var url = this.buildUrl('add');
                var param = page.form;
                param.opts_text = '正在新增...';
                param.module = this.module;
                UI.post(url, param, (result) => {
                    page.onQuery();
                });
            },
            getId: function(row) {
                Debug.log('config', this.config);
                if(row == null) {
                    row = this.page.currentRow; 
                }
                if(row == null) {
                    console.error("获取当前列失败", row);
                }
                var id = row[this.config.idName];
                if(id == null) {
                    console.error("获取ID失败", id);
                }
                return id;
            },
            onEditConfirm: function () {
                console.log('on edit confirm');
                var url = this.buildUrl('edit');
                var param = page.form;
                console.log('edit', param);
                param[this.config.idName] = this.getId();
                param.opts_text = '正在编辑...';
                param.module = this.module;
                UI.post(url, param, (result) => {
                    page.onQuery();
                });
            },
            onDeleteConfirm: function() {
                var page = this.page;
                console.log('on delete confirm');
                var url = this.buildUrl('delete');
                var id = this.getId();
				var opts_text = '正在删除...';
                var param = { id, opts_text };
                param.module = this.module;
                console.log( 'delete param', param);
                UI.post(url, param, (result) => {
                    page.onQuery();
                });
            },
            onPaginChange : function() {
                console.log('opPaginChange');
                page.onQuery();
            }
        };
        initPage(page, service);
        
        return service;
    };

    var Core = {
        // 带校验的接口请求 - 任何请求都走该校验
        post: function(url, param, _call, type) {
            var app = window.App;
            type = type || 'json';
            $.post(url, param, function(result) {
                // if(_final != null) {
                //     _final(result);
                // }
                // console.log('result', result);
                if(Util.isString(result)) {
                    _call(result);
                    return;
                }
                if(result.status == "success") {

                    // TODO 成功的不提示
                    // app.$message({
                    //     message: result.msg,
                    //     type: 'success'
                    // });
                } else if(result.status == "failure") {
                    if(app != null) {
                        app.$message({
                            message: result.msg,
                            type: 'error'
                        });
                        
                        console.error(result);
                        if(result.msg == '用户未登录') {
                            app.openLoginDialog();
                        }
                    }
                }
                _call(result);
            }, type);
        },
        // 获取并发加载器
        getMultiLoader: function() {
            var multiLoader = {
                _succ: null,
                loadSize : 0,
                loaderArr: [],
                loadAll : function() {
                    this.loadSize ++;
                    if(this.loadSize >= this.loaderArr.length) {
                        console.log('loadAll success');
                        this._succ();
                    }
                },
                add: function(_loaderArr) {
                    this.loaderArr = _loaderArr;
                },
                execute: function(_success) {
                    this._succ = _success;
                    for(var i in this.loaderArr) {
                        var _func = this.loaderArr[i];
                        _func(() => {
                            this.loadAll();
                        });
                    }
                }
            };
            return multiLoader;
        },
        inArray: function(arr, data) {
            for(var i in arr) {
                if(arr[i] == data) {
                    return true;
                }
            }
            return false;
        },
        getService: function(page, config) {
            if(page == null) {
                console.error("页面 page 不能为空");
                return;
            }
            // initPage(page);
            return getService(page, config);
        },
        checkResult: function(result) {
            if(result == null) {
                UI.warning( "系统异常：result is null" );
                return false;
            }
            if(result.status == "failure") {
                // vue.$message({
                //     message: result.msg,
                //     type: 'error'
                // });
                UI.warning( result.msg );
                return false;
            }
            return true;
        },
        getRoutePath: function() {
            // location.href;
        },
        getDom: function(select) {
            if(select.indexOf('#') != -1) {
                var id = select.substring(1);
                return document.getElementById(id);
            } else {
                console.error("暂时只支持 byId");
            }
        },
        calcMaxWidth: function(width) {
            if(width.indexOf('%') != -1) {
                var rate = Number( width.replace('%', '') ) / 100;
                return document.body.clientWidth * rate + 'px'
            } else if(width.indexOf('px') != -1) {
                return width;
            } else {
                return width + 'px';
            }
        },
        getHeadHeight: function() {
            return 80;
        },
        getTagHeight: function() {
            return 40;
        },
        getClientHeight: function() {
            return document.body.clientHeight;
        },
        calcMaxHeight: function(height) {
            if(height.indexOf('%') != -1) {
                var rate = Number( height.replace('%', '') ) / 100;
                return document.body.clientHeight * rate + 'px'
            } else if(height.indexOf('px') != -1) {
                return height;
            } else {
                return height + 'px';
            }
        },
        get(key) {
            return localStorage.getItem(key);
        },
    
        put(key, value) {
            localStorage.setItem(key, value);
        },
        bind2(page, key, value) {
            // if(page.watchMap == null) {
            //     page.watchMap = {};
            // }
            if(page.watch == null) {
                page.watch = {};
            }
            this.bind(page.watch, key, value);
        },
        /**
         * 绑定
         * @param {*} page 
         * @param {*} key 
         * @param {*} value 默认值
         */
         bind(watch, key, value) {
            // console.log('bind.watch', watch);

            // 1. 构建监听函数
            var oldWatch;
            if(watch[key] != null) {
                oldWatch = watch[key];
            }
            

            if(Util.isBaseType(value)) {
                watch[key] = function(newValue, oldValue) {
                    // console.log('watch ' + key + 'change: ' + newValue);
                    Core.put(key, newValue);
                    if(oldWatch != null ) {
                        oldWatch(newValue, oldValue)
                    }
                };
            } else {
                // console.log('bind object ' + key);
                watch[key] = {
                    handler(newValue, oldValue) {
                        var json = JSON.stringify(newValue);
                        Core.put(key, json);

                        if(oldWatch != null) {
                            oldWatch(newValue, oldValue)
                        }
                    },
                    immediate: true,
                    deep: true
                }
            }

            // 2. 第一次取值解析
            if(Core.get(key) != null) {
                var localValue = Core.get(key);
                
                if(localValue.indexOf('{') != -1) {
                    return JSON.parse(localValue);
                }
                
                return localValue;
            } else {
                return value;
            }
        },
        waitRef: function(refs, name, _call, _error, _key) {
            var i = 0;
            var timer = setInterval(() => {
                i ++;
                if(i == 100) {
                    console.error('waitRef 超过一秒');
                    clearInterval(timer);
                    
                    if(_error != null) { _error(); }
                    
                    return;
                }
                var ref = refs[name];
                if(ref != null) {
                    _call(ref);
                    clearInterval(timer);
                }
            }, 10);
        },
    };
    
    var Load = function(option) {
        var options = Load.options;
        console.log("原始vue单页参数", option);
        var name = option.methods.name();
        options[name] = option;
        if(option.watch == null) {
            option.watch = {};
        }
        option.methods.bind = function(key, value) {
            var watchMap = option.watch;
            return Data.bind(watchMap, key, value);
        };
        console.log("改造后的vue单页参数", option);
        return option;
    };

    Load.options = {};

    Load.option = function(name) {
        return Load.options[name];
    };

    window.Core = Core;
    window.Load = Load; 
    window.P = Load;

}());